package com.example.lj.uav.utils;

import android.content.Context;
import android.os.Environment;

import com.example.lj.uav.view.ManualFlightActivity;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class PayloadUtils {
    private static Context context;
    private int mPId;
    private String PATH_LOGCAT;
    public  boolean isRunning = false;
    private PayloadUtils.LogDumper mLogDumper = null;

    private static class PayloadUtilsInstance {
        private static final PayloadUtils INSTANCE = new PayloadUtils();
    }

    public static PayloadUtils getInstance(Context c) {
        if (context != null)
            return PayloadUtils.PayloadUtilsInstance.INSTANCE;
        context = c;
        return PayloadUtils.PayloadUtilsInstance.INSTANCE;
    }

    private PayloadUtils() {
        init();
        mPId = android.os.Process.myPid();
    }

    private void init() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // 优先保存到SD卡中
            PATH_LOGCAT = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + File.separator + "HEQ/payload";
        } else {
            // 如果SD卡不存在，就保存到本应用的目录下
            PATH_LOGCAT = context.getFilesDir().getAbsolutePath()
                    + File.separator + "HEQ";
        }
        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void start() {
        if (mLogDumper == null)
            mLogDumper = new PayloadUtils.LogDumper(String.valueOf(mPId), PATH_LOGCAT);
        if (!isRunning) {
            mLogDumper.start();
            isRunning = true;
        }
    }

    public void stop() {
        if (mLogDumper != null && isRunning) {
            mLogDumper.stopLogs();
            mLogDumper = null;
            isRunning = false;
        }
    }

    private class LogDumper extends Thread {

        private Process logcatProc;
        private BufferedReader mReader = null;
        private boolean mRunning = true;
        private String mPID;
        private FileOutputStream out = null;

        public LogDumper(String pid, String dir) {
            mPID = pid;
            try {
                out = new FileOutputStream(new File(dir, "payload-"
                        + MyDate.getTime() + ".txt"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        public void stopLogs() {
            mRunning = false;
        }

        @Override
        public void run() {
            try {
                mReader = new BufferedReader(new InputStreamReader(
                        logcatProc.getInputStream()), 1024);
                String line = null;
                while (mRunning && (line = mReader.readLine()) != null) {
                    if (!mRunning) {
                        break;
                    }
                    if (line.length() == 0) {
                        continue;
                    }
                    if (out != null && line.contains(mPID)) {
                        out.write((MyDate.getTime() + "  " + line + "\n")
                                .getBytes());
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (logcatProc != null) {
                    logcatProc.destroy();
                    logcatProc = null;
                }
                if (mReader != null) {
                    try {
                        mReader.close();
                        mReader = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    out = null;
                }
            }
        }
    }

    InputStream inputStream;

    public void initStream(ManualFlightActivity activity) {
        activity.setPayloadCallBack(new CallBack() {
            @Override
            public void setData(String s) {
                try {
                    inputStream = new ByteArrayInputStream(s.getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public interface CallBack {
        void setData(String s);

    }

    public InputStream getInputStream() {
        return inputStream;
    }
}
